package com.zhenyi.jiahua.index.admin;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jiahua.common.model.JhStaff;
import com.jiahua.common.model.JhStudent;
import com.jiahua.common.model.JhTeachRecord;
import com.zhenyi.jiahua.index.JHController;

public class TeachingRecordController extends JHController {

	@Override
	public void list() {
		super.list();
		String startDate = getStartToday();
		String endDate = getEndToday();
		Kv kv = Kv.create();
		kv.set("startDate", startDate);
		kv.set("endDate", endDate);
		setAttr("startDate", startDate);
		setAttr("endDate", endDate);

		Long staffId = getParaToLong("staffId");
		Long studentId = getParaToLong("studentId");

		if (studentId == null && staffId == null) {
			renderError(404);
			return;
		}

		if (staffId != null) {
			setAttr("staffId", staffId);
			kv.set("staffId", staffId);
		}
		if (studentId != null) {
			setAttr("studentId", studentId);
			kv.set("studentId", studentId);
			JhStudent student = JhStudent.dao.findById(studentId);
			setInfoItem(student);
		}
		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHFindTeachingRecord", kv);
		Page<Record> pages = Db.use("jiahua").paginate(getPage(), PAGE_SIZE, sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/jh/admin/teaching/list.html");
	}

	@Override
	public void info() {
		super.info();
		Long studentId = getParaToLong("studentId");
		JhStudent student = JhStudent.dao.findById(studentId);
		setAttr("student", student);
		setAttr("studentId", studentId);
		render("/jh/admin/teaching/info.html");
	}

	@Override
	public void submit() {
		Long recordId = getParaToLong("recordId", 0L);
		String content = getParaRelaceN("content");
		Long studentId = getParaToLong("studentId");
		if (studentId == null) {
			renderMsg("保存失败");
			return;
		}

		JhTeachRecord record = JhTeachRecord.dao.findById(recordId);
		if (record == null) {
			record = new JhTeachRecord();
			record.save();
		}
		JhStaff staff = getStaff();
		Long staffId = staff.getId();
		record.setContent(content);
		record.setStudentId(studentId);
		record.setStaffId(staffId);
		record.update();
		renderSuccess();
	}

}
